#include "mq_demo.h"
#include <iostream>
#include <csignal>
#include <atomic>

std::atomic<bool> running{true};

void signalHandler(int signal)
{
    std::cout << "\nReceived signal " << signal << ", shutting down..." << std::endl;
    running = false;
}

int main(int argc, char *argv[])
{
    // 注册信号处理
    std::signal(SIGINT, signalHandler);
    std::signal(SIGTERM, signalHandler);

    try
    {
        // 解析命令行参数
        std::string name_server = "192.168.31.125:9876"; // 默认NameServer
        std::string topic = "shangrao_in_small";         // 默认主题
        int send_interval_ms = 2000;                     // 默认发送间隔2秒

        if (argc > 1)
            name_server = argv[1];
        if (argc > 2)
            topic = argv[2];
        if (argc > 3)
            send_interval_ms = std::stoi(argv[3]);

        std::cout << "=== RocketMQ Demo Configuration ===" << std::endl;
        std::cout << "NameServer: " << name_server << std::endl;
        std::cout << "Topic: " << topic << std::endl;
        std::cout << "Send Interval: " << send_interval_ms << "ms" << std::endl;
        std::cout << "===================================" << std::endl;

        // 创建MQ演示实例
        MQDemo demo(name_server, topic, send_interval_ms);

        // 启动发送循环
        demo.start();
        std::cout << "MQ Demo is running. Press Ctrl+C to stop." << std::endl;
        if (!demo.isRunning())
        {
            std::cerr << "Failed to initialize MQ Demo!" << std::endl;
            return 1;
        }
        std::cout << "MQ Demo is running. Press Ctrl+C to stop." << std::endl;

        // 主循环
        while (running)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        // 停止演示
        demo.stop();
    }
    catch (const std::exception &e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    std::cout << "MQ Demo finished." << std::endl;
    return 0;
}